package com.zxw.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zxw.common.web.annotation.InitInsertInfo;
import com.zxw.common.web.util.JwtUtils;
import com.zxw.user.domain.dto.RoleBtnDTO;
import com.zxw.user.domain.entity.RoleButton;
import com.zxw.user.domain.vo.RoleButtonUpdateVO;
import com.zxw.user.mapper.RoleButtonMapper;
import com.zxw.user.service.RoleButtonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Xuewei.Zhang
 * @since 2022-02-27
 */
@Service
@RequiredArgsConstructor
public class RoleButtonServiceImpl extends ServiceImpl<RoleButtonMapper, RoleButton> implements RoleButtonService {

    private final RoleButtonMapper roleButtonMapper;

    @Override
    public Map<String, Map> getRoleBtnByRoleName(List<String> roleNames) {
        Long companyId = JwtUtils.getCompanyId();
        List<RoleBtnDTO> roleBtnDTOList = roleButtonMapper.getRoleBtnByRoleName(companyId, roleNames);
        return this.btnProvider(roleBtnDTOList);
    }

    /**
     * 返回当前角色拥有的按钮权限信息
     *
     * @param roleBtnDTOList
     * @return
     */
    private Map<String, Map> btnProvider(List<RoleBtnDTO> roleBtnDTOList) {
        Map<String, Map> map = new ConcurrentHashMap<>();// key功能模块 value功能模块
        for (int i = 0; i < roleBtnDTOList.size(); i++) {
            RoleBtnDTO roleBtnDTO = roleBtnDTOList.get(i);
            String functionalKey = roleBtnDTO.getFunctionalModule();
            Long value = roleBtnDTO.getIdentifier();
            if (ObjectUtil.isEmpty(value))
                continue;
            if (StrUtil.isNotBlank(functionalKey) && map.containsKey(functionalKey)) {
                Map functionalMap = map.get(functionalKey);
                functionalMap.put(value, value);
            } else {
                Map<Long, Long> btnIdentiferMap = new ConcurrentHashMap<>();// btn的value
                btnIdentiferMap.put(value, value);// 组装btn标识map
                map.put(functionalKey, btnIdentiferMap);// 组装key-“功能模块” 的所有btn标识map
            }
        }
        return map;
    }


    @Override
    public List<Long> getBtnIdsByRoleIdAndMenuId(Long roleId, Long menuId) {
        Long companyId = JwtUtils.getCompanyId();
        List<Long> btnIds = roleButtonMapper.getBtnIdByRoleIdAndMenuIdAndCompanyId(roleId, menuId, companyId);
        return btnIds;
    }



    @Override
    @InitInsertInfo
    public void batchUpdate(RoleButtonUpdateVO roleButtonUpdateVO) {
        Long companyId = roleButtonUpdateVO.getCompanyId();
        Long roleId = roleButtonUpdateVO.getRoleId();
        Long menuId = roleButtonUpdateVO.getMenuId();
        List<Long> btnIds = roleButtonUpdateVO.getBtnIds();

        // 比对数据，是否发生变化
        List<Long> oldBtnIds = this.getBtnIdsByRoleIdAndMenuId(roleButtonUpdateVO.getRoleId(), roleButtonUpdateVO.getMenuId());
        List<Long> sortBtnIds = btnIds.stream().sorted().collect(Collectors.toList());
        List<Long> sortOldBtnIds = oldBtnIds.stream().sorted().collect(Collectors.toList());
        Boolean changeFlag = CollectionUtil.isEqualList(sortBtnIds, sortOldBtnIds);
        if (changeFlag) {
            return;
        }

        // 删除此次保存移除的按钮权限
        if (CollectionUtil.isNotEmpty(sortOldBtnIds)) {
            List<Long> removeIds = sortOldBtnIds.stream().filter(oldId -> !sortBtnIds.contains(oldId)).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(removeIds)) {
                this.remove(new LambdaQueryWrapper<RoleButton>()
                        .eq(RoleButton::getCompanyId, companyId)
                        .eq(RoleButton::getMenuId, menuId)
                        .eq(RoleButton::getRoleId, roleId)
                        .in(RoleButton::getBtnId, removeIds)
                );
            }
        }

        // 新增此次保存 不存在的按钮权限
        if (CollectionUtil.isNotEmpty(sortBtnIds)) {
            List<Long> newBtnIds = sortBtnIds.stream().filter(oldId -> !sortOldBtnIds.contains(oldId)).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(newBtnIds)) {
                List<RoleButton> addRoleButtons = new ArrayList<>();
                for (int i = 0; i < newBtnIds.size(); i++) {
                    RoleButton roleButton = new RoleButton();
                    BeanUtils.copyProperties(roleButtonUpdateVO, roleButton);
                    roleButton.setBtnId(newBtnIds.get(i));
                    addRoleButtons.add(roleButton);
                }
                this.saveBatch(addRoleButtons, addRoleButtons.size());
            }
        }
    }


}
